<template>
  <div class="edit-department">
    <a-modal
      width="800px"
      :title="updateTitles"
      :visible="visible"
      :confirm-loading="confirmLoading"
      :maskClosable="false"
      @ok="handleSubmit"
      @cancel="handleCancel"
    >
      <a-spin :spinning="spinning" tip="正在加载数据中...">
        <a-form :form="form">
          <a-row :gutter="10">
            <a-col :span="12">
              <a-form-item label="上级部门" :labelCol="{ span: 8 }" :wrapperCol="{ span: 16 }">
                <a-tree-select
                  v-decorator="[
                    'PID',
                    {
                      rules: [
                        {
                          type: 'number',
                          required: true,
                          message: '请选择上级部门',
                          whitespace: true,
                          trigger: 'change',
                        },
                      ],
                    },
                  ]"
                  allowClear
                  show-search
                  treeNodeFilterProp="title"
                  :replaceFields="{
                    children: 'children',
                    title: 'DepartmentName',
                    key: 'ID',
                    value: 'ID',
                  }"
                  :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
                  :tree-data="parentTreeList"
                  placeholder="请选择上级部门"
                  searchPlaceholder="输入部门名称进行筛选"
                >
                </a-tree-select>
              </a-form-item>
            </a-col>
            <!-- fix: 修改时部门名称不能修改 -->
            <a-col :span="12">
              <a-form-item label="部门名称" :labelCol="{ span: 8 }" :wrapperCol="{ span: 16 }">
                <a-input
                  v-decorator="[
                    'DepartmentName',
                    {
                      rules: [
                        { required: true, message: '', whitespace: true, trigger: 'change' },
                        { validator: validateDeptName },
                      ],
                    },
                  ]"
                  autocomplete="off"
                  placeholder="请输入部门名称"
                />
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="部门等级" :labelCol="{ span: 8 }" :wrapperCol="{ span: 16 }">
                <a-select
                  v-decorator="[
                    'BBDJ',
                    {
                      rules: [
                        {
                          type: 'number',
                          required: false,
                          message: '请输入部门等级',
                          whitespace: true,
                          trigger: 'change',
                        },
                      ],
                    },
                  ]"
                  placeholder="请选择部门等级"
                >
                  <a-select-option v-for="item in levelList" :key="item.ID" :value="item.ID">{{
                    item.CSMC
                  }}</a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="部门地址" :labelCol="{ span: 8 }" :wrapperCol="{ span: 16 }">
                <a-input v-decorator="['BBDZ']" allowClear autocomplete="off" placeholder="请输入部门地址" />
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="部门电话" :labelCol="{ span: 8 }" :wrapperCol="{ span: 16 }">
                <a-input
                  v-decorator="[
                    'BBDH',
                    {
                      rules: [
                        { required: true, message: '请输入部门电话', whitespace: true, trigger: 'change' },
                        { validator: validateFixedTelephone },
                      ],
                    },
                  ]"
                  allowClear
                  autocomplete="off"
                  placeholder="请输入部门电话"
                />
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="负责人姓名" :labelCol="{ span: 8 }" :wrapperCol="{ span: 16 }">
                <a-input
                  v-decorator="['DepartmentHead']"
                  allowClear
                  placeholder="请输入负责人姓名"
                  autocomplete="off"
                />
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="负责人联系电话" :labelCol="{ span: 8 }" :wrapperCol="{ span: 16 }">
                <a-input
                  v-decorator="[
                    'FZRDH',
                    {
                      rules: [
                        { required: true, message: '请输入负责人联系电话', whitespace: true, trigger: 'change' },
                        { validator: validateTelephone },
                      ],
                    },
                  ]"
                  allowClear
                  autocomplete="off"
                  placeholder="请输入负责人联系电话"
                />
              </a-form-item>
            </a-col>
          </a-row>
        </a-form>
      </a-spin>
    </a-modal>
  </div>
</template>

<script>
import pick from 'lodash.pick'
import { setDepartments, getDepartmentSelect } from '@/api/system'
import { getParameterSelect } from '@/api/common'
import { validFixedTelphone, validTelphone } from '@/utils/validate'
export default {
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    propsData: {
      type: Object,
      default: () => {
        return {}
      }
    }
  },
  data () {
    return {
      confirmLoading: false,
      spinning: false,
      labelCol: { span: 8 },
      wrapperCol: { span: 16 },
      parentTreeList: [{
        DepartmentName: '无',
        ID: 0,
        key: 0,
        children: []
      }],
      levelList: [],
      form: this.$form.createForm(this, { name: 'department' })
    }
  },
  watch: {
    'propsData': function () {
      this.fetchDepartment()
    }
  },
  computed: {
    updateTitles: function () {
      const { propsData: { type } } = this
      if (type === 'add') {
        return '新增部门'
      } else if (type === 'addChild') {
        return '新增子部门'
      } else {
        return '修改部门'
      }
    }
  },
  methods: {
    fetchDepartment () {
      this.spinning = true
      const { propsData: { type, record }, form: { setFieldsValue } } = this
      const tree = new Promise((resolve, reject) => {
        getDepartmentSelect({
          type: 'ddepartemnt',
          Contype: this.$store.getters.loginName
        }).then(res => {
          resolve(res.data)
        })
      })
      const category = new Promise((resolve, reject) => {
        getParameterSelect({ ClassKey: 'BMDJ' }).then(res => {
          console.log('1111111111111',res);
          resolve(res.data)
        })
      })
      Promise.all([tree, category]).then(res => {
        this.parentTreeList[0].children = res[0]
        console.log(this.parentTreeList)
        this.levelList = res[1]
        if (type === 'addChild') {
          setFieldsValue({ PID: record.ID })
        }
        if (type === 'add' || type === 'addChild') return
        record.BBDJ = record.BBDJ ? Number(record.BBDJ) : undefined
        this.$nextTick(() => {
          setFieldsValue(pick(record, ['PID', 'DepartmentName', 'BBDJ', 'BBDZ', 'BBDH', 'DepartmentHead', 'FZRDH']))
        })
      }).catch(() => {
        this.$message.error('网络请求失败, 请稍后重试')
      }).finally(() => {
        this.spinning = false
      })
    },

    handleSubmit () {
      const { form: { validateFields }, propsData: { type, record }, $message } = this
      validateFields((err, values) => {
        if (!err) {
          this.confirmLoading = true
          const submitData = Object.assign({}, values, {
            Contype: this.$store.getters.loginName,
            Type: '0'
          })
          if (type === 'update') {
            submitData.ID = record.ID
          }
          setDepartments({
            State: type === 'update' ? 'update' : 'add',
            department: submitData
          }).then(res => {
            if (res.code === 200) {
              $message.success(res.message || '提交成功', 3)
              this.handleCancel()
              this.$parent.$parent.$refs.table.refresh(true)
            } else {
              $message.error(res.message || '提交失败', 3)
            }
          }).catch((err) => {
            $message.error(err, 3)
          }).finally(() => {
            this.confirmLoading = false
          })
        }
      })
    },
    handleCancel () {
      this.form.resetFields()
      this.$emit('update:visible', false)
    },
    validateDeptName (rule, value, callback) {
      if (!value) {
        callback(new Error('请输入部门名称'))
      }
      callback()
    },
    validateFixedTelephone (rule, value, callback) {
      if (!value) {
        callback()
      }
      if (!validFixedTelphone(value)) {
        callback(new Error('部门电话输入有误, 请检查后重新输入'))
      }
      callback()
    },
    validateTelephone (rule, value, callback) {
      if (!value) {
        callback()
      }
      if (!validTelphone(value)) {
        callback(new Error('联系电话输入有误, 请检查后重新输入'))
      }
      callback()
    }
  }
}
</script>
